using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class Delay : MonoBehaviour
{	
	internal class DelayInfo
	{
		public DelayDelegate onComplete;
		public float time;
		public bool enabled;
	}
	
	public delegate void DelayDelegate();
	
	//DelayDelegate onComplete;
	//float time = 0f;
	List<DelayInfo> _delayList;
	  
	void Awake()
	{
		_delayList = new List<DelayInfo>();
		//enabled = false;
	}
	
	void Update()
	{
		/*
		time -= Time.deltaTime;
		if( time < 0f )
		{
			onComplete();
			enabled = false;
		}
		*/
		DelayInfo _currDelay;
		for( int i = _delayList.Count - 1; i >= 0; i-- )
		{	
			_currDelay = _delayList[i];
			_currDelay.time -= Time.deltaTime;
			if( _currDelay.time < 0f )
			{
				_currDelay.onComplete();
				_delayList.Remove(_currDelay);
				_currDelay = null;
			}
		}
		
	}
	
	static public void Perform( GameObject go, float _time, DelayDelegate _delegate )
	{
		Delay comp = go.GetComponent<Delay>();
		#if UNITY_FLASH
		if ((object)comp == null) comp = (Delay)go.AddComponent<Delay>();
		#else
		if (comp == null) comp = go.AddComponent<Delay>();
		#endif
		
		DelayInfo _info = new DelayInfo();
		
		_info.time = _time;
		_info.onComplete = _delegate;
		_info.enabled = true; 
		
		comp._delayList.Add(_info);
		/*		
		comp.time = _time;
		comp.onComplete = _delegate;
		comp.enabled = true; 
		*/
		//return comp;
	}
}



